package com.xxl.sso.core.util;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import com.xxl.sso.core.model.LoginInfo;
import java.util.Date;
import java.util.UUID;

public class JwtUtil {

    // JWT签名密钥（实际项目中应从配置文件读取）
    private static final String SECRET_KEY = "your-secret-key-12345678901234567890123456789012";
    
    // JWT过期时间（毫秒，例如7天）
    private static final long EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;

    /**
     * 生成JWT token
     */
    public static String generateToken(LoginInfo loginInfo) {
        String a = "";
        // 创建JWT声明
        JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
                .subject(loginInfo.getUserName())
                .claim("userId", loginInfo.getUserId())
                .claim("username", loginInfo.getUserName())
                .claim("roleList", loginInfo.getRoleList())
                .claim("permissionList", loginInfo.getPermissionList())
                .jwtID(UUID.randomUUID().toString())
                .issueTime(new Date())
                .expirationTime(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .build();

        // 创建JWS头
        JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);
        
        // 创建签名JWT对象
        SignedJWT signedJWT = new SignedJWT(header, claimsSet);

        try {
            // 创建签名器并签名
            JWSSigner signer = new MACSigner(SECRET_KEY.getBytes());
            signedJWT.sign(signer);

        }  catch (Exception e) {
            e.printStackTrace();
        }
        // 返回序列化后的token字符串
        return signedJWT.serialize();
    }

    /**
     * 验证JWT token
     */
    public static boolean validateToken(String token) {
        try {
            // 解析JWT
            SignedJWT signedJWT = SignedJWT.parse(token);
            
            // 创建验证器并验证签名
            JWSVerifier verifier = new MACVerifier(SECRET_KEY.getBytes());
            if (!signedJWT.verify(verifier)) {
                return false;
            }
            
            // 检查token是否过期
            JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet();
            Date expirationTime = claimsSet.getExpirationTime();
            if (expirationTime != null && new Date().after(expirationTime)) {
                return false;
            }
            
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从JWT中获取用户信息
     */
    public static LoginInfo getUserInfoFromToken(String token) throws Exception {
        SignedJWT signedJWT = SignedJWT.parse(token);
        JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet();
        
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setUserId(claimsSet.getStringClaim("userId"));
        loginInfo.setUserName(claimsSet.getStringClaim("username"));
        
        return loginInfo;
    }
}